//
//  STWebViewController.m
//  SportHome
//
//  Created by stoneobs on 16/12/14.
//  Copyright © 2016年 stoneobs. All rights reserved.
//

#define SCREEN_HEIGHT  [UIScreen mainScreen].bounds.size.height
#define SCREEN_FRAME  [UIScreen mainScreen].bounds
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width


#import "STWebViewController.h"

@interface STWebViewController ()<WKNavigationDelegate>

@property(nonatomic, strong) NSString             *h5String;

@property(nonatomic, strong) UIProgressView       *progressView;
@property(nonatomic, strong) UIView               *loadingView;
@end

@implementation STWebViewController

- (instancetype)initWithUrl:(NSString *)url
{
    self = [super init];
    if (self) {
        self.urlStr = url;
    }
    return self;
}
- (instancetype)initWithH5String:(NSString *)h5String{
    self = [super init];
    if (self) {
        self.h5String = h5String;
    }
    return self;
}
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}
#pragma mark --Geter And Setter
- (UIColor *)progressTintColor
{
    if (_progressTintColor) {
        return _progressTintColor;
    }
    return TM_ThemeBackGroundColor;
}
- (UIColor *)progressBackgroundColor
{
    if (_progressTintColor) {
        return _progressTintColor;
    }
    return [UIColor whiteColor];
}
#pragma mark --vc生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [TMUtils sendGetLookAwardRequest];
    self.title = @"正在加载...";
    self.view.backgroundColor = [UIColor whiteColor];
   // self.webView.sc
    NSString *jScript =
    @"user-scalable = no;var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
    
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    
  //  [wkUController addUserScript:wkUScript];
    
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    
    wkWebConfig.userContentController = wkUController;
    
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, [TMUtils navgationBarBootom], UIScreenWidth, [TMUtils tabBarTop] - [TMUtils navgationBarBootom]) configuration:wkWebConfig];
    [self.view addSubview:self.webView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (ios11 && [self.webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.webView.scrollView setContentInsetAdjustmentBehavior:@(2)];
    }
    
    if (self.urlStr) {
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]
                                  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                 
                                                  timeoutInterval:10];
        [self.webView loadRequest:request];
    }
    if (self.h5String) {
        [self.webView loadHTMLString:self.h5String baseURL:nil];
    }

    self.webView.navigationDelegate = self;
    
    
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, [TMUtils navgationBarBootom], SCREEN_WIDTH, 2)];
    self.progressView.backgroundColor = self.progressBackgroundColor;
    self.progressView.progressTintColor = self.progressTintColor;
    [self.view addSubview:self.progressView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    //菊花
    UIActivityIndicatorView * juhuaView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [juhuaView startAnimating];
    self.loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    juhuaView.center = CGPointMake(_loadingView.frame.size.width/2, _loadingView.frame.size.width/2);
    self.loadingView.layer.cornerRadius = 15;
    self.loadingView.center = self.view.center;
    self.loadingView.backgroundColor = [UIColor grayColor];
    [self.loadingView addSubview:juhuaView];
  //  [self.view addSubview:self.loadingView];
    
    BOOL page = [[NSUserDefaults standardUserDefaults] boolForKey:pageKey];
    if(page){
        [self configSubView];
    }
    
    if (BBThemeColorManger.isBlack) {
        self.webView.opaque = NO;
        self.view.backgroundColor = [BBThemeColorManger manger].backGroundColor;
        self.webView.backgroundColor = UIColor.clearColor;
    }

   
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    STButton * upButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:20
                                           backgroundColor:[TM_backgroundColor colorWithAlphaComponent:0.6]
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"up"]];
    upButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    upButton.bottom = UIScreenHeight / 2 - 20;
    upButton.right = UIScreenWidth  -20 ;
    [upButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedUpButton];
    }];
    [self.view addSubview:upButton];
    
    STButton * downButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                    title:nil
                                               titleColor:nil
                                                titleFont:0
                                             cornerRadius:20
                                          backgroundColor:[TM_backgroundColor colorWithAlphaComponent:0.6] 
                                          backgroundImage:nil
                                                    image:[UIImage imageNamed:@"down"]];
    downButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    downButton.top = UIScreenHeight / 2 + 20;
    downButton.right = UIScreenWidth  -20 ;
    [downButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcteddownButton];
    }];
    [self.view addSubview:downButton];
}
#pragma mark --kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if (object==self.webView&&[keyPath isEqualToString:@"estimatedProgress"]) {
        //NSLog(@"%f",self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;

    }
    if (object==self.webView&&[keyPath isEqualToString:@"title"]) {
        
        self.title = self.webView.title;
    }
}
#pragma mark --WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    decisionHandler(WKNavigationActionPolicyAllow);//允许跳转


}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{

    //完成
    self.loadingView.hidden = YES;
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    if (BBThemeColorManger.isBlack) {
        [webView evaluateJavaScript:@"document.body.style.backgroundColor=\"black\"" completionHandler:nil];
        // 改变网页内容文字颜色
        [webView evaluateJavaScript:@"document.body.style.webkitTextFillColor=\"gray\"" completionHandler:nil];
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='black'"  completionHandler:nil];
        [webView evaluateJavaScript:@"javascript:(function(){var styleElem=null,doc=document,ie=doc.all,fontColor=50,sel='body,body *';styleElem=createCSS(sel,setStyle(fontColor),styleElem);function setStyle(fontColor){var colorArr=[fontColor,fontColor,fontColor];return'background-color:#000 !important;color:RGB('+colorArr.join('%,')+'%) !important;'};function createCSS(sel,decl,styleElem){var doc=document,h=doc.getElementsByTagName('head')[0],styleElem=styleElem;if(!styleElem){s=doc.createElement('style');s.setAttribute('type','text/css');styleElem=ie?doc.styleSheets[doc.styleSheets.length-1]:h.appendChild(s)};if(ie){styleElem.addRule(sel,decl)}else{styleElem.innerHTML='';styleElem.appendChild(doc.createTextNode(sel+' {'+decl+'}'))};return styleElem}})();" completionHandler: nil];
    }

    



}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    self.loadingView.hidden = YES;
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    NSLog(@"%@",error);


}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{

    self.loadingView.hidden = YES;
    NSLog(@"%@",error);
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.loadingView.hidden = YES;
           // [SVProgressHUD showErrorWithStatus:@"加载失败,请输入正确的网址"];
        });

    });

}
#pragma mark --Action Method
- (void)onSelctedUpButton{
    
    CGFloat y = self.webView.scrollView.contentOffset.y;
   // CGFloat maxHeight = self.webView.scrollView.contentSize.height;
    
    CGFloat screenHeight = [TMUtils tabBarTop] - [TMUtils navgationBarBootom];
    
    CGFloat finshY = y - screenHeight;
    if (finshY < 0) {
        finshY = 0;
    }
    [self.webView.scrollView setContentOffset:CGPointMake(0, finshY) animated:YES];
}
- (void)onSelcteddownButton{
    CGFloat y = self.webView.scrollView.contentOffset.y;
    CGFloat maxHeight = self.webView.scrollView.contentSize.height;
    
    CGFloat screenHeight = [TMUtils tabBarTop] - [TMUtils navgationBarBootom];
    
    CGFloat finshY = y + screenHeight;
    if (finshY > maxHeight) {
        finshY = maxHeight;
    }
    [self.webView.scrollView setContentOffset:CGPointMake(0, finshY) animated:YES];
}
@end
